//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package upgrade

import (
	"context"
	"math"

	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/user_dao"
	"github.com/dchest/uniuri"
)

type UpToVer12 struct{}

func (up *UpToVer12) Exec(ctx context.Context) error {
	userItemList, err := user_dao.UserInfoDao.ListAll(ctx, false, 0, 0, math.MaxInt64)
	if err != nil {
		return err
	}
	for _, userItem := range userItemList {
		exist, err := user_dao.UserSecretDao.Exist(ctx, userItem.UserId)
		if err != nil {
			return err
		}
		if !exist {
			secret := uniuri.NewLenChars(32, []byte("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
			err = user_dao.UserSecretDao.Insert(ctx, &user_dao.UserSecretDbItem{
				UserId: userItem.UserId,
				Secret: secret,
			})
			if err != nil {
				return err
			}
		}
	}
	return dao.VersionDao.Set(ctx, dao.VERSION_KEY_SCHEMA, 12)
}
